package com.lb.shopguide.ui.fragment.boss;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterBossMessage;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.BossMessageBean;
import com.lb.shopguide.entity.MsgAttachedContent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.fragment.boss.market.FragmentActivityApply;
import com.lb.shopguide.ui.fragment.boss.market.FragmentMarketing;
import com.lb.shopguide.ui.fragment.boss.market.FragmentUseTemplate;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by kang on 2017/12/25.
 */

public class FragmentBossMessage extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private ArrayList<MultiItemEntity> mBossMessageBeanList;

    private AdapterBossMessage mAdapter;


    public static FragmentBossMessage newInstance() {
        return new FragmentBossMessage();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_boss_message;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        refresh();
    }

    @Override
    public void initView() {
        ctb.setTvTitle("消息盒");
        ctb.setLeftImageSrc(R.drawable.iv_back);
        ctb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop();
            }
        });

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view_boss, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无消息");
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new AdapterBossMessage(mBossMessageBeanList, false);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).paintProvider(mAdapter).build());

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BossMessageBean bossMessageBean = (BossMessageBean) mBossMessageBeanList.get(position);
                if (bossMessageBean.getMsgItemTypeCode() == AppConstant.MESSAGE_BALANCE_NOT_ENOUGH) {
                    start(FragmentChargeInMoney.newInstance());
                } else if (bossMessageBean.getMsgItemTypeCode() == AppConstant.MESSAGE_ACTIVITY_APPLY) {
                    start(FragmentActivityApply.newInstance(bossMessageBean.getMsgAttachedContent().getApplyCode(), bossMessageBean.getMsgAttachedContent().getMsgId()));
                } else if (bossMessageBean.getMsgItemTypeCode() == AppConstant.MESSAGE_MARKET_ADVICE) {
                    MsgAttachedContent content = bossMessageBean.getMsgAttachedContent();
                    ((FragmentMarketing) getParentFragment()).start(FragmentUseTemplate.newInstance(content.getTemplateCode(), content.getTemplateName(), content.getStoreCode(), content.getMsgId()));
                } else {
                    startToActivityPage(bossMessageBean.getMsgLinkUrl(), bossMessageBean.getMsgTitle());
                }
            }
        });
        mAdapter.setOnMsgCloseListener(new AdapterBossMessage.OnMsgManagerListener() {
            @Override
            public void onMsgClose(String msgCode) {

            }

            @Override
            public void onImMsgRead() {

            }

            @Override
            public void onCheckMsg() {
            }

            @Override
            public void gotoActivity(String url, String title) {
                startToActivityPage(url, title);
            }
        });
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentBossMessage.class.getName();
    }

    private void sendRequestGetMessageList() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArrayBossMessage = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonArrayBossMessage.size() != 0) {
                        for (JsonElement obj : jsonArrayBossMessage) {
                            BossMessageBean bean = JsonUtil.getGson().fromJson(obj, BossMessageBean.class);
                            mBossMessageBeanList.add(bean);
                        }
                        mAdapter.setNewData(mBossMessageBeanList);
                    } else {
                        bindEmpty();
                    }
                    finishRefresh();
                }
            }
        };
        ApiMethodBoss.getBossMessage(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        if (mError) {
            mAdapter.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapter.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    private void bindEmpty() {
        mBossMessageBeanList.clear();
        mAdapter.setNewData(mBossMessageBeanList);

        mNoData = true;
        onRefresh();
    }

    private void refresh() {
        mBossMessageBeanList = new ArrayList<>();
        sendRequestGetMessageList();
    }


    private void startToActivityPage(String url, String name) {
        Intent intent = new Intent(mContext, ActivityActivityDetail.class);
        Bundle bundle = new Bundle();
        if (url.contains("?")) {
            bundle.putString(AppConstant.WEB_URL, url + "&token=" + mUserConfigManager.getUserToken() + "&type=android");
        } else {
            bundle.putString(AppConstant.WEB_URL, url + "?token=" + mUserConfigManager.getUserToken() + "&type=android");
        }
        bundle.putString(AppConstant.WEB_TITLE, name);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
